# coding: utf-8

"""
@version: python3.6
@author: 噢啦嘿嘿
@contact: jian.zhou@360che.com
@software: PyCharm
@file: collect_manage.py
@time: 2021/4/13 16:18
"""
import copy
import operator

from sqlalchemy import func, desc, or_

from application import db
from application.apps.collect.service import Sum_collect
from application.libs import list_include_dic, sort_listdic
from application.libs.enum import demand
from application.models.models import CollectSum, Personnel_Rate, PersonnelRateGroupList
from application.models.venus_models import CdbTask, CdbProjectCreateByTask
from models import Collect


# def collect_sum():
#     """
#     # 项目的工时、参与项目数、准入/出率、按时准入/出率、发布准时率、发布成功率、需求变更次数，非实时查询
#     # :return:
#     # """
#     collectsum_l = db.session.query(CollectSum).filter(CollectSum.status != 0).order_by(
#         desc(CollectSum.id)).all()
#     res_l = {}
#     if collectsum_l:
#         collectsum_l_data = {"business": [], "project_nums": [], "count_times": [], "access_rate": [], "must_rate": [],
#                              "access_on_rate": [], "must_out_rate": [], "release_success": [], "repair_rate": [],
#                              "bug_rate": [], "Invalid_rate": [], "release_rate": [], "change": [], }
#         demand_change_data = []
#         for i in collectsum_l:
#             if i.business in collectsum_l_data["business"]:
#                 break
#             demand_change_data.append({"value": i.change, "name": i.business})
#             collectsum_l_data["business"].append(i.business)
#             collectsum_l_data["project_nums"].append(i.project_nums)
#             collectsum_l_data["count_times"].append(i.count_times)
#             collectsum_l_data["access_rate"].append(rate_swich_num(i.access_rate))
#             collectsum_l_data["must_rate"].append(rate_swich_num(i.must_rate))
#             collectsum_l_data["access_on_rate"].append(rate_swich_num(i.access_on_rate))
#             collectsum_l_data["must_out_rate"].append(rate_swich_num(i.must_out_rate))
#             collectsum_l_data["release_success"].append(rate_swich_num(i.release_success))
#             collectsum_l_data["repair_rate"].append(rate_swich_num(i.repair_rate))
#             collectsum_l_data["bug_rate"].append(rate_swich_num(i.bug_rate))
#             collectsum_l_data["Invalid_rate"].append(rate_swich_num(i.Invalid_rate))
#             collectsum_l_data["release_rate"].append(rate_swich_num(i.release_rate))
#             collectsum_l_data["change"].append(i.change)
#         dic_projects_working_time = {}
#         # 项目的工时、参与项目数
#         setProjectsWorkingTimeData(dic_projects_working_time, collectsum_l_data)
#         res_l["dic_projects_working_time"] = dic_projects_working_time
#         # 项目的准入、出率
#         dic_admittance_out = {}
#         setAdmittanceOutData(dic_admittance_out, collectsum_l_data)
#         res_l["dic_admittance_out"] = dic_admittance_out
#         # 项目的按时准入、出率、发布准时率、发布成功率
#         dic_on_time_release = {}
#         setOnTimeReleaseData(dic_on_time_release, collectsum_l_data)
#         res_l["dic_on_time_release"] = dic_on_time_release
#         # 需求及变更次数
#         demand_change_data = sorted(demand_change_data, key=operator.itemgetter('value'))
#         res_l["demand_change"] = {"name": "需求及变更次数", "data": demand_change_data}
#         # 需求类型统计
#         demand_type = {}
#         setDemandTypeData(demand_type)
#         res_l["demand_type"] = demand_type
#         # bug率统计
#         bug_rate = setBugRateData(collectsum_l_data)
#         res_l["bug_rate"] = bug_rate
#         # bug修复率统计
#         bug_repair_rate = setBugRepairRateData(collectsum_l_data)
#         res_l["bug_repair_rate"] = bug_repair_rate
#     return res_l


def collect_sum_real_time(data):
    """
    2021-05-18 项目总览修改为实时查询collect表
    项目的工时、参与项目数、准入/出率、按时准入/出率、发布准时率、发布成功率、需求变更次数
    :return:
    """
    s_date = data["start_time"]
    e_date = data["end_time"]
    collectsum_l = Sum_collect.collect_sum_real_time(s_date, e_date)  # 直接调用计算脚本内容，已注释此方法中的collect_sum表入库部分，返回所需数据
    collectsum_l_data = {"business": [], "project_nums": [], "count_times": [], "access_rate": [], "must_rate": [],
                         "access_on_rate": [], "must_out_rate": [], "release_success": [], "repair_rate": [],
                         "bug_rate": [], "Invalid_rate": [], "release_rate": [], "change": [], }
    res_l = {}
    if collectsum_l:
        demand_change_data = []
        for i in collectsum_l:  # 由于collectsum_l必定有数据，所以不再判断为空
            if i["business"] in collectsum_l_data["business"]:
                break
            demand_change_data.append({"value": i["change"], "name": i["business"]})
            collectsum_l_data["business"].append(i["business"])
            collectsum_l_data["project_nums"].append(i["project_nums"])
            collectsum_l_data["count_times"].append(i["count_times"])
            collectsum_l_data["access_rate"].append(rate_swich_num(i["access_rate"]))
            collectsum_l_data["must_rate"].append(rate_swich_num(i["must_rate"]))
            collectsum_l_data["access_on_rate"].append(rate_swich_num(i["access_on_rate"]))
            collectsum_l_data["must_out_rate"].append(rate_swich_num(i["must_out_rate"]))
            collectsum_l_data["release_success"].append(rate_swich_num(i["release_success"]))
            collectsum_l_data["repair_rate"].append(rate_swich_num(i["repair_rate"]))
            collectsum_l_data["bug_rate"].append(rate_swich_num(i["bug_rate"]))
            collectsum_l_data["Invalid_rate"].append(rate_swich_num(i["Invalid_rate"]))
            collectsum_l_data["release_rate"].append(rate_swich_num(i["release_rate"]))
            collectsum_l_data["change"].append(i["change"])
        dic_projects_working_time = {}
        # 项目的工时、参与项目数
        setProjectsWorkingTimeData(dic_projects_working_time, collectsum_l_data)
        res_l["dic_projects_working_time"] = dic_projects_working_time
        # 项目的准入、出率
        dic_admittance_out = {}
        setAdmittanceOutData(dic_admittance_out, collectsum_l_data)
        res_l["dic_admittance_out"] = dic_admittance_out
        # 项目的按时准入、出率、发布准时率、发布成功率
        dic_on_time_release = {}
        setOnTimeReleaseData(dic_on_time_release, collectsum_l_data)
        res_l["dic_on_time_release"] = dic_on_time_release
        # 需求及变更次数
        demand_change_data = sorted(demand_change_data, key=operator.itemgetter('value'))
        res_l["demand_change"] = {"name": "需求及变更次数", "data": demand_change_data}
        # 需求类型统计
        demand_type = {}
        setDemandTypeData(demand_type, s_date, e_date)
        res_l["demand_type"] = demand_type
        # bug率统计
        bug_rate = setBugRateData(collectsum_l_data)
        res_l["bug_rate"] = bug_rate
        # bug修复率统计
        bug_repair_rate = setBugRepairRateData(collectsum_l_data)
        res_l["bug_repair_rate"] = bug_repair_rate
    else:
        res_l = {
            "bug_rate": {"legend_data": [], "legend_selected": {}, "series_data": {}, "xAxis_data": []},
            "bug_repair_rate": {"legend_data": [], "legend_selected": {}, "series_data": {}, "xAxis_data": []},
            "dic_admittance_out": {"legend_data": [], "legend_selected": {}, "series_data": {}, "xAxis_data": []},
            "dic_on_time_release": {"legend_data": [], "legend_selected": {}, "series_data": {}, "xAxis_data": []},
            "dic_projects_working_time": {"series_project_num": [], "series_project_time": [], "xAxis_data": [],
                                          "yAxis_num_interval": 0, "yAxis_num_max": 0, "yAxis_time_interval": 0,
                                          "yAxis_time_max": 0},
            "demand_type": {"legend_data": [], "series_data": {}, "xAxis_type": []},
            "demand_change": {"data": []},
        }
    return res_l


def collect_trend():
    """
    质量趋势
    :return:
    """
    collect_trend_l = db.session.query(CollectSum).filter(CollectSum.nature_week == 1).order_by(
        desc(CollectSum.id)).all()  # 获取自然周的数据
    res_l = {}
    business_dic = {"整体": {"bug_rate": [], "Invalid_rate": [],
                           "release_rate": [], "inflow_demand": [], "online_demand": [],
                           "complete_demand": []}}
    y_w = []
    for j in collect_trend_l:  # 即便之后再添加新的业务线也不影响数据显示，所以先进行一次循环
        if j.business in business_dic.keys():  # 存在业务之后直接停止循环，或者直接查库直接去status = 1的数据也可，不想再查库了
            break
        business_dic[j.business] = {"bug_rate": [], "Invalid_rate": [],
                                    "release_rate": [],
                                    "inflow_demand": [], "online_demand": [],
                                    "complete_demand": []
                                    }
    inflow_demand_nums, online_demand_nums, complete_demand_nums = 0, 0, 0
    # 周
    get_week_sum_data(business_dic, collect_trend_l, complete_demand_nums, inflow_demand_nums, online_demand_nums, y_w)
    for i in business_dic:
        for o in business_dic[i]:
            business_dic[i][o] += [0] * (len(y_w) - len(business_dic[i][o]))
    business = list(business_dic.keys())
    false_l = [False] * len(business)
    b_f = list_include_dic(business, false_l)
    b_f["整体"] = True
    p_d_series_data, b_r_series_data, i_r_series_data, r_r_series_data = {}, {}, {}, {}

    for i in business_dic.keys():
        p_d_series_data[i + "流入需求"] = business_dic[i]["inflow_demand"]  # 流入需求
        p_d_series_data[i + "流出需求"] = business_dic[i]["complete_demand"]  # 完成需求
        p_d_series_data[i + "上线需求"] = business_dic[i]["online_demand"]  # 上线需求
        b_r_series_data[i] = business_dic[i]["bug_rate"]
        i_r_series_data[i] = business_dic[i]["Invalid_rate"]
        r_r_series_data[i] = business_dic[i]["release_rate"]
    p_d_t_business = list(p_d_series_data.keys())
    p_d_t_false_l = [False] * len(p_d_t_business)
    p_d_b_f = list_include_dic(p_d_t_business, p_d_t_false_l)
    p_d_b_f["整体流入需求"], p_d_b_f["整体流出需求"], p_d_b_f["整体上线需求"] = True, True, True
    res_l["project_demand_trend"] = {"legend_data": p_d_t_business, "legend_selected": p_d_b_f,
                                     "xAxis_data": y_w, "series_data": p_d_series_data}  # 自然周项目需求流动趋势图
    res_l["bug_rate_trend"] = {"legend_data": business, "legend_selected": b_f,
                               "xAxis_data": y_w, "series_data": b_r_series_data}  # 自然周bug率趋势图
    res_l["invalid_rate_trend"] = {"legend_data": business, "legend_selected": b_f,
                                   "xAxis_data": y_w, "series_data": i_r_series_data}  # 自然周无效修改率趋势图
    res_l["release_rate_trend"] = {"legend_data": business, "legend_selected": b_f,
                                   "xAxis_data": y_w, "series_data": r_r_series_data}  # 自然周发布成功率趋势图
    return res_l


def get_week_sum_data(business_dic, collect_trend_l, complete_demand_nums, inflow_demand_nums, online_demand_nums, y_w):
    for i in collect_trend_l:
        updated_time = i.updated_time
        week = updated_time.isocalendar()
        year, weeks = week[0], week[1]
        w = str(year) + "年第" + str(weeks) + "周"+"("+str(updated_time.month)+"."+str(updated_time.day)+")"
        if w not in y_w:
            y_w.append(w)
            business_dic["整体"]["bug_rate"].append(rate_swich_num(i.whole_bug_rate))
            business_dic["整体"]["Invalid_rate"].append(rate_swich_num(i.whole_Invalid_rate))
            business_dic["整体"]["release_rate"].append(rate_swich_num(i.whole_release_rate))
            if len(y_w) > 1:
                business_dic["整体"]["inflow_demand"].append(copy.copy(inflow_demand_nums))
                business_dic["整体"]["online_demand"].append(copy.copy(online_demand_nums))
                business_dic["整体"]["complete_demand"].append(copy.copy(complete_demand_nums))
                inflow_demand_nums, online_demand_nums, complete_demand_nums = 0, 0, 0
        inflow_demand_nums += int(i.inflow_demand)
        online_demand_nums += int(i.online_demand)
        complete_demand_nums += int(i.complete_demand)
        business_dic[i.business]["bug_rate"].append(rate_swich_num(i.bug_rate))
        business_dic[i.business]["Invalid_rate"].append(rate_swich_num(i.Invalid_rate))
        business_dic[i.business]["release_rate"].append(rate_swich_num(i.release_rate))
        business_dic[i.business]["inflow_demand"].append(i.inflow_demand)
        business_dic[i.business]["online_demand"].append(i.online_demand)
        business_dic[i.business]["complete_demand"].append(i.complete_demand)
    business_dic["整体"]["inflow_demand"].append(inflow_demand_nums)
    business_dic["整体"]["online_demand"].append(online_demand_nums)
    business_dic["整体"]["complete_demand"].append(complete_demand_nums)


def get_month_sum_data(business_dic, collect_trend_l, complete_demand_nums, inflow_demand_nums, online_demand_nums,
                       y_w):
    bug_rate, Invalid_rate, release_rate, inflow_demand, online_demand, complete_demand, \
    whole_bug_rate, whole_Invalid_rate, whole_release_rate = [], [], [], 0, 0, 0, [], [], []
    y_d = []
    for i in collect_trend_l:
        updated_time_date = i.updated_time.date()
        w = str(updated_time_date.year) + "年" + str(updated_time_date.month) + "月"
        if i.updated_time not in y_d:
            y_d.append(i.updated_time)
            whole_bug_rate.append(float(i.whole_bug_rate))
            whole_Invalid_rate.append(float(i.whole_Invalid_rate))
            whole_release_rate.append(float(i.whole_release_rate))
        if w not in y_w:
            y_w.append(w)
            if len(y_w) > 1:
                business_dic["整体"]["bug_rate"].append(rate_swich_num(str(sum(whole_bug_rate) / len(whole_bug_rate))))
                business_dic["整体"]["Invalid_rate"].append(
                    rate_swich_num(str(sum(whole_Invalid_rate) / len(whole_Invalid_rate))))
                business_dic["整体"]["release_rate"].append(
                    rate_swich_num(str(sum(whole_release_rate) / len(whole_release_rate))))
                business_dic["整体"]["inflow_demand"].append(copy.copy(inflow_demand_nums))
                business_dic["整体"]["online_demand"].append(copy.copy(online_demand_nums))
                business_dic["整体"]["complete_demand"].append(copy.copy(complete_demand_nums))
                business_dic[i.business]["bug_rate"].append(rate_swich_num(str(sum(bug_rate) / len(bug_rate))))
                business_dic[i.business]["Invalid_rate"].append(
                    rate_swich_num(str(sum(Invalid_rate) / len(Invalid_rate))))
                business_dic[i.business]["release_rate"].append(
                    rate_swich_num(str(sum(release_rate) / len(release_rate))))
                business_dic[i.business]["inflow_demand"].append(copy.copy(inflow_demand))
                business_dic[i.business]["online_demand"].append(copy.copy(online_demand))
                business_dic[i.business]["complete_demand"].append(copy.copy(complete_demand))
                inflow_demand_nums, online_demand_nums, complete_demand_nums = 0, 0, 0
                bug_rate, Invalid_rate, release_rate, inflow_demand, online_demand, complete_demand, \
                whole_bug_rate, whole_Invalid_rate, whole_release_rate = [], [], [], 0, 0, 0, [], [], []
        inflow_demand_nums += int(i.inflow_demand)
        online_demand_nums += int(i.online_demand)
        bug_rate.append(float(i.bug_rate))
        Invalid_rate.append(float(i.Invalid_rate))
        release_rate.append(float(i.release_rate))
        inflow_demand += float(i.inflow_demand)
        online_demand += float(i.online_demand)
        complete_demand += float(i.complete_demand)
    business_dic["整体"]["bug_rate"].append(rate_swich_num(str(sum(whole_bug_rate) / len(whole_bug_rate))))
    business_dic["整体"]["Invalid_rate"].append(rate_swich_num(str(sum(whole_Invalid_rate) / len(whole_Invalid_rate))))
    business_dic["整体"]["release_rate"].append(rate_swich_num(str(sum(whole_release_rate) / len(whole_release_rate))))
    business_dic["整体"]["inflow_demand"].append(copy.copy(inflow_demand_nums))
    business_dic["整体"]["online_demand"].append(copy.copy(online_demand_nums))
    business_dic["整体"]["complete_demand"].append(copy.copy(complete_demand_nums))
    business_dic[i.business]["bug_rate"].append(rate_swich_num(str(sum(bug_rate) / len(bug_rate))))
    business_dic[i.business]["Invalid_rate"].append(rate_swich_num(str(sum(Invalid_rate) / len(Invalid_rate))))
    business_dic[i.business]["release_rate"].append(rate_swich_num(str(sum(release_rate) / len(release_rate))))
    business_dic[i.business]["inflow_demand"].append(copy.copy(inflow_demand))
    business_dic[i.business]["online_demand"].append(copy.copy(online_demand))
    business_dic[i.business]["complete_demand"].append(copy.copy(complete_demand))


# def nr_yy_data(dic, y_w, dic_zx, dic_hd):
#     """
#     内容运营数据
#     :param dic: 内容运营数据结构
#     :param y_w: 自然周数据
#     :param dic_zx: 资讯数据
#     :param dic_hd: 互动数据
#     :return:
#     """
#     l = len(y_w)
#     for i in range(l):
#         for j in dic.keys():
#             if j in ["inflow_demand", "online_demand", "complete_demand"]:
#                 v = (float(dic_zx[j][i]) + float(dic_hd[j][i]))
#             else:
#
#                 v = (float(dic_zx[j][i]) + float(dic_hd[j][i])) / 2
#             dic[j].append(float('%.4f' % v))
#     return dic


def setBugRateData(collectsum_l_data):
    """
    bug率统计
    :param collectsum_l_data:
    :return:
    """
    bug_rate = {"legend_data": ['项目bug率', "整体bug率"], "legend_selected": {'项目bug率': True, "整体bug率": True}}

    collect_p_data = db.session.query(func.sum(Collect.P1), func.sum(Collect.P2),
                                      func.sum(Collect.P3), func.sum(Collect.P4),
                                      func.sum(Collect.spendtime)).all()
    sum_bug_rate = float(collect_p_data[0][0]) * 3 + float(collect_p_data[0][1]) * 2 + float(
        collect_p_data[0][2]) * 1 + float(
        collect_p_data[0][3]) * 0.5
    whole_bug_rate = sum_bug_rate / float(collect_p_data[0][4])
    whole_bug_rate = rate_swich_num(str(whole_bug_rate))
    whole_bug_rate_l = [whole_bug_rate] * len(collectsum_l_data["bug_rate"])
    a = list(map(eval, collectsum_l_data["bug_rate"]))
    d_bbr = list_include_dic(collectsum_l_data["business"], a)
    d_bbr = sort_listdic(d_bbr)
    final_collectsum_l_data = list(d_bbr.keys())
    bug_rate["xAxis_data"] = final_collectsum_l_data
    bug_rate["series_data"] = {"项目bug率": list(d_bbr.values()),
                               "整体bug率": whole_bug_rate_l}
    return bug_rate


def setBugRepairRateData(collectsum_l_data):
    """
    bug修复率统计
    :param collectsum_l_data:
    :return:
    """
    bug_repair_rate = {"legend_data": ['项目bug修复率', "项目bug无效修复率"],
                       "legend_selected": {'项目bug修复率': True, "项目bug无效修复率": True}}
    a = list(map(eval, collectsum_l_data["repair_rate"]))
    d_bbr = list_include_dic(collectsum_l_data["business"], a)
    d_bbr = sort_listdic(d_bbr)
    final_collectsum_l_data = list(d_bbr.keys())
    a = list(map(eval, collectsum_l_data["Invalid_rate"]))
    d_bbnr = list_include_dic(collectsum_l_data["business"], a)
    bugNoRepairRate = [d_bbnr[b] for b in final_collectsum_l_data]
    bug_repair_rate["xAxis_data"] = final_collectsum_l_data
    bug_repair_rate["series_data"] = {"项目bug修复率": list(d_bbr.values()),
                                      "项目bug无效修复率": bugNoRepairRate}
    return bug_repair_rate


def setDemandTypeData(demand_type, s_date, e_date):
    """
    需求类型统计(注意：如果计算数据不是当时执行的，需求类型统计图会和项目的参与数有偏差，这个需求类型统计的数量是最新的)
    :param demand_type:
    :return:
    """
    Collect_parm = [Collect.pstatus != 1, Collect.status != 0]
    if s_date != '' and e_date != '':
        Collect_parm.append(or_(Collect.begindate >= s_date, Collect.onlinedate >= s_date, Collect.enddate >= s_date))
        Collect_parm.append(or_(Collect.begindate <= e_date, Collect.onlinedate <= e_date, Collect.enddate <= e_date))
    collect = db.session.query(Collect.group, Collect.ptype).filter(*Collect_parm).all()
    l = []
    series_old_data = {"验收需求": [], "标准需求": [], "线上bug": [], "紧急发版": [], "生产事故": [], '总量': []}
    series_data = {"验收需求": [], "标准需求": [], "线上bug": [], "紧急发版": [], "生产事故": [], '总量': []}
    for i in collect:
        if i.group in l:
            continue
        l.append(i.group)
        c = [demand(o.ptype).name for o in collect if o.group == i.group]
        series_old_data['验收需求'].append(c.count('验收需求'))
        series_old_data['标准需求'].append(c.count('标准需求'))
        series_old_data['线上bug'].append(c.count('线上bug'))
        series_old_data['紧急发版'].append(c.count('紧急发版'))
        series_old_data['生产事故'].append(c.count('生产事故'))
        series_old_data['总量'].append(len(c))
    l_btype = list_include_dic(l, series_old_data['总量'])
    l_btype = sort_listdic(l_btype)
    v_l = list(l_btype.values())
    for i in v_l:
        i_num = series_old_data['总量'].index(i)
        series_data['验收需求'].append(series_old_data['验收需求'][i_num])
        series_data['标准需求'].append(series_old_data['标准需求'][i_num])
        series_data['线上bug'].append(series_old_data['线上bug'][i_num])
        series_data['紧急发版'].append(series_old_data['紧急发版'][i_num])
        series_data['生产事故'].append(series_old_data['生产事故'][i_num])
    demand_type["xAxis_type"] = list(l_btype.keys())
    demand_type["legend_data"] = ["验收需求", "标准需求", "线上bug", "紧急发版", "生产事故"]
    demand_type["series_data"] = series_data


def rate_swich(num):
    """
    百分比转换
    :param num:str （0.3211）
    :return:  -- or 32.11%
    """
    if '-' in num:
        return num
    elif '未上线' in num:
        return '--'
    else:
        return "%.2f%%" % (float(num) * 100)


def setOnTimeReleaseData(dic_on_time_release, collectsum_l_data):
    """
    项目的按时准入、出率、发布准时率、发布成功率
    :param dic_on_time_release:
    :param collectsum_l_data:
    :return:
    """
    dic_on_time_release["legend_data"] = ['按时准入率', '按时准出率', '发布准时率']
    dic_on_time_release["legend_selected"] = {'按时准入率': True, '按时准出率': True, '发布准时率': False}
    dic_on_time_release["xAxis_data"] = collectsum_l_data["business"]

    dic_on_time_release["series_data"] = {"按时准入率": collectsum_l_data["access_on_rate"],
                                          "按时准出率": collectsum_l_data["must_out_rate"],
                                          "发布准时率": collectsum_l_data["release_success"]}


def setAdmittanceOutData(dic_admittance_out, collectsum_l_data):
    """
    项目的准入、出率
    :param dic_admittance_out:
    :param collectsum_l_data:
    :return:
    """
    dic_admittance_out["legend_data"] = ['准入率', '准出率', '发布成功率']
    dic_admittance_out["legend_selected"] = {'准入率': True, '准出率': False, "发布成功率": True}

    a = list(map(eval, collectsum_l_data["release_rate"]))
    d_bpn = list_include_dic(collectsum_l_data["business"], a)
    d_bpn = sort_listdic(d_bpn)
    final_business = list(d_bpn.keys())
    collectsum_l_series_data = []
    collectsum_l_must_rate = []
    for i in final_business:
        i_num = collectsum_l_data["business"].index(i)
        collectsum_l_series_data.append(collectsum_l_data["access_rate"][i_num])
        collectsum_l_must_rate.append(collectsum_l_data["must_rate"][i_num])
    dic_admittance_out["xAxis_data"] = final_business
    dic_admittance_out["series_data"] = {"准入率": collectsum_l_series_data, "准出率": collectsum_l_must_rate,
                                         "发布成功率": list(d_bpn.values())}


def setProjectsWorkingTimeData(dic_projects_working_time, collectsum_l_data):
    """
    项目的工时、参与项目数
    :param dic_projects_working_time:
    :param collectsum_l_data:
    :return:
    """
    # a = list(map(eval, collectsum_l_data["project_nums"]))  # 数组中的元素是字符串，转成数字，便于后面的排序,感觉zip函数更合适些
    d_bp = list_include_dic(collectsum_l_data["business"], collectsum_l_data["project_nums"])
    d_bt = list_include_dic(collectsum_l_data["business"], collectsum_l_data["count_times"])
    d_bp = sort_listdic(d_bp)
    final_business = list(d_bp.keys())
    final_project_nums = list(d_bp.values())
    final_project_time = [d_bt[i] for i in final_business]
    dic_projects_working_time["xAxis_data"] = final_business
    dic_projects_working_time["series_project_num"] = final_project_nums
    # dic_projects_working_time["series_project_time"] = list(map(eval, final_project_time))
    dic_projects_working_time["series_project_time"] = final_project_time
    dic_projects_working_time["yAxis_num_max"] = 5 * int(
        (max(dic_projects_working_time["series_project_time"]) + 4) / 5)
    dic_projects_working_time["yAxis_num_interval"] = dic_projects_working_time["yAxis_num_max"] / 5
    dic_projects_working_time["yAxis_time_max"] = 5 * int(
        (max(dic_projects_working_time["series_project_num"]) + 4) / 5)
    dic_projects_working_time["yAxis_time_interval"] = dic_projects_working_time["yAxis_time_max"] / 5
    # dic_projects_working_time["legend_data"] = ['参与项目数', '总工时']


def rate_swich_num(num):
    """
    百分比转换
    :param num:str （0.3211）
    :return:  -- or 32.11%
    """

    if not num and num != 0:
        return '--'
    elif isinstance(num, float) or isinstance(num, int):
        return "%.2f" % (float(num) * 100)
    elif '-' in num:
        return num
    elif '未上线' in num:
        return '--'
    else:
        return "%.2f" % (float(num) * 100)


def personnel_rate(group):
    """
    # 人员工时
    # :return:
    # """
    parm = []
    if group != 'all':
        parm.append(Personnel_Rate.group == group)
    collectsum_l = db.session.query(Personnel_Rate).filter(*parm).all()
    l = {}
    if collectsum_l:
        collectsum_l_data = {"id": [], "name": [], "bug_rate": [], "bug_num": []}
        demand_change_data = []
        for i in collectsum_l:
            demand_change_data.append({"value": i.id, "name": i.name, "rate": i.bug_rate, "bug_num": i.bug_num})
            collectsum_l_data["id"].append(i.id)
            collectsum_l_data["name"].append(i.name)
            collectsum_l_data["bug_num"].append(i.bug_num)
            bug_rate = i.bug_rate * 100
            collectsum_l_data["bug_rate"].append(float('%.4f' % bug_rate))
        dic_projects_working_time = {}
        # 项目的工时、参与项目数
        setProjectsWorkingTimeDataPersonnel(dic_projects_working_time, collectsum_l_data)
        l["dic_projects_working_time"] = dic_projects_working_time

    return l


def personnel_rate_group_list():
    """
    # 人员bug率各组别名称
    # :return:
    # """
    collectsum_l = db.session.query(PersonnelRateGroupList).all()
    demand_change_data = []
    if collectsum_l:
        for i in collectsum_l:
            demand_change_data.append({"id": i.id, "group": i.group})
    return demand_change_data


def setProjectsWorkingTimeDataPersonnel(dic_projects_working_time, collectsum_l_data):
    """
    :param dic_projects_working_time:
    :param collectsum_l_data:
    :return:
    """
    a = list(map(eval, collectsum_l_data["bug_num"]))
    d_bp = list_include_dic(collectsum_l_data["name"], a)
    d_bt = list_include_dic(collectsum_l_data["name"], collectsum_l_data["bug_rate"])
    d_bp = sort_listdic(d_bp)
    final_business = list(d_bp.keys())
    final_project_nums = list(d_bp.values())
    final_project_time = [d_bt[i] for i in final_business]
    dic_projects_working_time["xAxis_data"] = final_business
    dic_projects_working_time["series_project_num"] = final_project_nums
    dic_projects_working_time["series_project_time"] = final_project_time
    dic_projects_working_time["yAxis_num_max"] = 5 * int(
        (max(dic_projects_working_time["series_project_time"]) + 4) / 5)
    dic_projects_working_time["yAxis_num_interval"] = dic_projects_working_time["yAxis_num_max"] / 5
    dic_projects_working_time["yAxis_time_max"] = 5 * int(
        (max(dic_projects_working_time["series_project_num"]) + 4) / 5)
    dic_projects_working_time["yAxis_time_interval"] = dic_projects_working_time["yAxis_time_max"] / 5
    dic_projects_working_time["legend_data"] = ["项目工时", "bug 率"]


#
# def personnel_working_hours_count():
#     cdbTask_result_sub = db.session.query(CdbTask.version).filter(CdbTask.category_business == "商业配合",
#                                                                   CdbTask.category_product == "广告系统").distinct().subquery()
#     # result = db.session.query(CdbTask).outerjoin(CdbProjectCreateByTask,
#     #                                              CdbProjectCreateByTask.task_id == CdbTask.id).filter(
#     #     CdbTask.category_business == "互动", CdbTask.category_product == "Android标准版",
#     #     CdbTask.version.in_(cdbTask_result_sub)).group_by(CdbTask.owner_uid, CdbProjectCreateByTask.project_id).all()
#     l = {}
#     l["username"] = personnel_working_hours_owner_uid_list()[0]
#     l["working_sum"] = personnel_working_hours_owner_uid_list()[1]
#     return l
#
# def personnel_working_hours_owner_uid_list():
#     cdbTask_result_sub = db.session.query(CdbTask.version).filter(CdbTask.category_business == "商业配合",
#                                                                   CdbTask.category_product == "广告系统").distinct().subquery()
#     result = db.session.query(CdbTask,OtMember.username).outerjoin(CdbProjectCreateByTask,
#                                                  CdbProjectCreateByTask.task_id == CdbTask.id).outerjoin(OtMember,
#                                                  OtMember.uid == CdbTask.owner_uid).filter(
#         CdbTask.category_business == "商业配合", CdbTask.category_product == "广告系统",
#         CdbTask.version.in_(cdbTask_result_sub)).group_by(CdbTask.owner_uid).all()
#     ll = []
#     namell = []
#     for i in result:
#         ll.append(i.CdbTask.owner_uid)
#         namell.append(i.username)
#     return (namell,personnel_working_hours_owner_uid(ll))
#
#
# def personnel_working_hours_owner_uid(li):
#     l = []
#     for o in li:
#         cdbTask_result_sub = db.session.query(CdbTask.version).filter(CdbTask.category_business == "商业配合",
#                                                                       CdbTask.category_product == "广告系统").distinct().subquery()
#         result = db.session.query(CdbTask).outerjoin(CdbProjectCreateByTask,
#                                                      CdbProjectCreateByTask.task_id == CdbTask.id).filter(
#             CdbTask.category_business == "商业配合", CdbTask.category_product == "广告系统", CdbTask.owner_uid == o,
#             CdbTask.version.in_(cdbTask_result_sub)).group_by(CdbTask.owner_uid, CdbProjectCreateByTask.project_id).all()
#
#         demand_change_data = []
#         for i in result:
#             ll = [i.plan_start_time.strftime("%Y-%m-%d"),i.plan_end_time.strftime("%Y-%m-%d")]
#             demand_change_data.append(ll)
#         l.append(personnel_working_hours_owner_uid_sum(demand_change_data))
#     return l
#
# def personnel_working_hours_owner_uid_sum(li):
#     ll = []
#     for o in li:
#         a = o[0]
#         b = o[1]
#         d1 = datetime.datetime.strptime(a, '%Y-%m-%d')
#         d2 = datetime.datetime.strptime(b, '%Y-%m-%d')
#         dev_time = (d2 - d1).days + 1
#         for i in range((d2 - d1).days):
#             d = d2 + datetime.timedelta(days=i)
#             if d.isoweekday() == 6 or d.isoweekday() == 7:
#                 dev_time -= 1
#         ll.append((dev_time * 8))
#     return (sum(ll))
#
#

def personnel_working_hours_count():
    idlist = db.session.query(CdbTask.id, CdbTask.version).filter(CdbTask.category_business == "互动",
                                                                  CdbTask.category_product == "Android标准版").distinct()
    id_list = []
    idversion_list = {}
    if idlist:
        for i in idlist:
            id_list.append(i.id)
            idversion_list[i.id] = i.version

    result = db.session.query(CdbTask).join(CdbProjectCreateByTask,
                                            CdbProjectCreateByTask.project_id == CdbTask.project_id,
                                            isouter=True).filter(
        CdbProjectCreateByTask.task_id.in_(id_list)).all()

    result_list = []
    idversion_list = {}
    if result:
        for i in result:
            idversion_list[i.owner_uid] = [i.plan_start_time, i.plan_end_time]
    return (idversion_list)


def personnel_working_hours_count_owner_id():
    result = db.session.query(CdbTask).filter()
